<template>
  <view style="height: 100vh;background-color: #F9FBFC;">
    <uni-nav-bar class="bar_title" shadow left-icon="left" rightText="新增" title="单位" @clickLeft="handleHomepage()"
      @clickRight="handleAdd()" fixed />
    <uni-search-bar :focus="true" v-model="queryParams.unitName" @confirm="handleSearch" @blur="handleSearch"
      @cancel="handleCancel" placeholder="请输入单位名称">
    </uni-search-bar>
    
    <scroll-view 
      class="list-container" 
      scroll-y="true" 
      @scrolltolower="loadMore"
      :style="{height: scrollHeight}"
    >
      <view class="card-container">
        <view class="card-wrap" v-for="item in unitList" :key="item.id" :class="getStatusClass(item.pushStatus)">
          <view class="card-header">
            <text class="unit-name">{{item.unitName}}</text>
            <view class="status-badge" :class="'status-'+item.pushStatus">
              {{getPushStatus(item.pushStatus)}}
            </view>
          </view>

          <view class="card-content">
            <view class="info-item">
              <uni-icons type="phone" size="16" color="#666"></uni-icons>
              <text class="info-text">消责人电话：{{ item.responsibleManTel }}</text>
            </view>

            <view class="action-row">
              <view class="status-text">
                <uni-icons type="notification" size="16" color="#666"></uni-icons>
                <text>推送状态：{{ getPushStatus(item.pushStatus) }}</text>
              </view>
              <view v-if="item.pushStatus != '2'" class="sync-btn" @click="handleSort(item.id)">
                <uni-icons type="refresh" size="14" color="#fff"></uni-icons>
                <text>推送</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <uni-load-more 
        :status="loadStatus" 
        :icon-size="16"
        :content-text="{
          contentdown: '上拉加载更多',
          contentrefresh: '正在加载...',
          contentnomore: '没有更多了'
        }"
      />
    </scroll-view>
  </view>
</template>

<script>
  import { listUnit, unitPush } from "@/api/system/unit"

  export default {
    data() {
      return {
        unitList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          unitName: ''
        },
        total: 0,
        loadStatus: 'more',
        isLoading: false,
        scrollHeight: 'calc(100vh - 180rpx)'
      }
    },
    created() {
      this.getList();
      this.calcScrollHeight();
    },
    methods: {
      calcScrollHeight() {
        const query = uni.createSelectorQuery().in(this);
        query.select('.bar_title').boundingClientRect(data => {
          const navBarHeight = data.height;
          query.select('.uni-searchbar').boundingClientRect(searchData => {
            const searchBarHeight = searchData.height;
            const systemInfo = uni.getSystemInfoSync();
            this.scrollHeight = `${systemInfo.windowHeight - navBarHeight - searchBarHeight}px`;
          }).exec();
        }).exec();
      },
      
      async getList(loadMore = false) {
        if (this.loadStatus === 'noMore' || this.isLoading) return;
        
        this.isLoading = true;
        this.loadStatus = 'loading';
        
        if (!loadMore) {
          this.queryParams.pageNum = 1;
        }

        try {
          const response = await listUnit(this.queryParams);
          
          if (loadMore) {
            this.unitList = [...this.unitList, ...response.rows];
          } else {
            this.unitList = response.rows;
          }
          
          this.total = response.total;
          
          // 判断是否还有更多数据
          if (this.unitList.length >= this.total || response.rows.length < this.queryParams.pageSize) {
            this.loadStatus = 'noMore';
          } else {
            this.loadStatus = 'more';
            this.queryParams.pageNum++;
          }
        } catch (error) {
          console.error('获取数据失败:', error);
          this.loadStatus = 'more';
        } finally {
          this.isLoading = false;
        }
      },
      
      loadMore() {
        this.getList(true);
      },
      
      handleSearch() {
        this.getList();
      },
      
      handleCancel() {
        this.queryParams.unitName = '';
        this.getList();
      },
      
      handleHomepage() {
        uni.reLaunch({
          url: '/pages/index'
        });
      },
      
      handleAdd() {
        uni.navigateTo({
          url: '/pages/system/unit/unitAdd'
        });
      },
      
      getStatusClass(status) {
        if (status == '0') return 'status-warning';
        if (status == '1') return 'status-error';
        if (status == '2') return 'status-success';
      },
      
      getPushStatus(val) {
        const statusMap = {
          '0': '未推送',
          '1': '推送失败',
          '2': '推送成功'
        };
        return statusMap[val] || '';
      },
      
      handleSort(id) {
        unitPush(id).then(() => {
          this.$modal.msgSuccess("推送成功！");
          this.getList();
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .uni-nav-bar-text {
    font-weight: 500;
  }

  .bar_title {
    font-weight: bold;
  }

  .list-container {
    width: 100%;
    box-sizing: border-box;
    -webkit-overflow-scrolling: touch;
  }

  .card-container {
    width: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #f7f8fa;

    .card-wrap {
      padding: 24rpx;
      border-radius: 16rpx;
      background-color: #FFF;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
      margin-bottom: 24rpx;
      transition: all 0.3s ease;
      border-left: 8rpx solid #ddd;

      &:active {
        transform: translateY(-2rpx);
        box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
      }

      &.status-success {
        border-left-color: #67c23a;

        .status-badge {
          background-color: #67c23a;
        }
      }

      &.status-warning {
        border-left-color: #e6a23c;

        .status-badge {
          background-color: #e6a23c;
        }
      }

      &.status-error {
        border-left-color: #f56c6c;

        .status-badge {
          background-color: #f56c6c;
        }
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        padding-bottom: 16rpx;
        border-bottom: 1rpx solid #f1f1f1;

        .unit-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .status-badge {
          font-size: 24rpx;
          padding: 4rpx 12rpx;
          border-radius: 20rpx;
          color: white;

          &.status-0 {
            background-color: #e6a23c;
          }

          &.status-1 {
            background-color: #f56c6c;
          }

          &.status-2 {
            background-color: #67c23a;
          }
        }
      }

      .card-content {
        .info-item {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;
          font-size: 28rpx;
          color: #666;

          .info-text {
            margin-left: 8rpx;
          }
        }

        .action-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 12rpx;
          border-top: 1rpx dashed #eee;

          .status-text {
            display: flex;
            align-items: center;
            font-size: 26rpx;
            color: #666;

            text {
              margin-left: 8rpx;
            }
          }

          .sync-btn {
            display: flex;
            align-items: center;
            padding: 6rpx 20rpx;
            border-radius: 30rpx;
            background-color: #409eff;
            color: white;
            font-size: 26rpx;

            text {
              margin-left: 6rpx;
            }
          }
        }
      }
    }
  }
</style>